package com.vmj.instructions.constants;

import com.vmj.classfile.entity.constantinfo.*;
import com.vmj.heap.VMClass;
import com.vmj.heap.ClassRef;
import com.vmj.heap.RuntimeConstantPool;
import com.vmj.heap.VMObject;
import com.vmj.heap.StringPool;
import com.vmj.rtda.Frame;
import com.vmj.rtda.OperandStack;

/**
 * Created by yangshoujun on 2017/8/27 下午12:35.
 */
public class LdcUtil {

    public static void ldc(Frame frame, int index) {
        OperandStack stack = frame.getOperandStack();
        RuntimeConstantPool cp = frame.getMethod().getClazz().getRuntimeConstantPool();
        VMClass clazz = frame.getMethod().getClazz();
        java.lang.Object constant = cp.getConstant(index).getValue();
        if(constant instanceof Integer) {
            stack.pushInt((Integer) constant);
        } else if(constant instanceof Float) {
            stack.pushFloat((Float) constant);
        } else if(constant instanceof Long) {
            stack.pushLong((Long) constant);
        } else if(constant instanceof Double) {
            stack.pushDouble((Double) constant);
        } else if(constant instanceof String) {
            String str = (String) constant;
            VMObject strObj = StringPool.getStringObject(clazz.getClassLoader(), str);
            stack.pushRef(strObj);
        } else if(constant instanceof ClassRef) {
            ClassRef ref = (ClassRef) constant;
            VMObject classObj = ref.resolvedClass().getjClass();
            stack.pushRef(classObj);
        } else if(constant instanceof ConstantFieldRefInfo) {
            stack.pushRef(constant);
        } else if(constant instanceof ConstantMethodRefInfo) {
            stack.pushRef(constant);
        } else if(constant instanceof ConstantInterfaceMethodRefInfo) {
            stack.pushRef(constant);
        } else {
            stack.pushRef(constant);
        }
    }
}
